#include "tabmanager.h"
#include "sqleditor.h"
#include <QTabWidget>
#include <QSqlDatabase>
#include <QSqlQueryModel>
#include <QVBoxLayout>
#include <QWidget>
#include <QApplication>
#include <QMessageBox>
#include <QCompleter>
#include <QStringListModel>

TabManager::TabManager(QWidget *parent)
    : QTabWidget(parent)
    , m_tabCounter(0)
{
    setupUI();
}

int TabManager::addQueryTab(const QString &title)
{
    QString tabTitle = title.isEmpty() ? tr("Query %1").arg(++m_tabCounter) : title;
    
    SqlEditor *editor = new SqlEditor();
    editor->setDatabase(m_database);
    
    // 连接信号和槽
    connect(editor, &SqlEditor::executeQuery, this, &TabManager::executeQuery);
    
    int index = addTab(editor, tabTitle);
    m_editors[index] = editor;
    
    // 设置可以关闭标签
    setTabsClosable(true);
    
    emit tabAdded(index);
    return index;
}

void TabManager::removeQueryTab(int index)
{
    if (index >= 0 && index < count()) {
        SqlEditor *editor = m_editors.take(index);
        if (editor) {
            delete editor;
        }
        
        removeTab(index);
        emit tabRemoved(index);
    }
}

SqlEditor* TabManager::getSqlEditor(int index) const
{
    return qobject_cast<SqlEditor*>(widget(index));
}

SqlEditor* TabManager::getCurrentSqlEditor() const
{
    return getSqlEditor(currentIndex());
}

void TabManager::setDatabase(const QSqlDatabase &db)
{
    m_database = db;
    
    // 更新所有编辑器的数据库连接
    for (SqlEditor *editor : m_editors.values()) {
        editor->setDatabase(db);
    }
}

void TabManager::executeQuery(const QString &query)
{
    // 转发查询执行信号
    emit executeQuery(query);
}

void TabManager::showQueryResults(QSqlQueryModel *model)
{
    // 在当前活动的SqlEditor中显示结果
    SqlEditor *editor = getCurrentSqlEditor();
    if (editor) {
        editor->onQueryExecuted(model);
    }
}

void TabManager::onTabCloseRequested(int index)
{
    removeQueryTab(index);
}

void TabManager::onCurrentTabChanged(int index)
{
    emit currentTabChanged(index);
}

void TabManager::setupUI()
{
    // 设置标签位置
    setTabPosition(QTabWidget::North);
    
    // 连接内部信号和槽
    connect(this, &QTabWidget::tabCloseRequested, this, &TabManager::onTabCloseRequested);
    connect(this, &QTabWidget::currentChanged, this, &TabManager::onCurrentTabChanged);
    
    // 添加第一个查询标签
    addQueryTab(tr("Query 1"));
    
    // 初始化自动补全数据
    setupAutoCompletion();
}

void TabManager::setupAutoCompletion()
{
    // 创建补全器
    QCompleter *completer = new QCompleter(this);
    
    // 设置SQL关键字列表
    QStringList sqlKeywords;
    sqlKeywords << "SELECT" << "FROM" << "WHERE" << "INSERT" << "INTO" 
                << "VALUES" << "UPDATE" << "SET" << "DELETE" << "JOIN"
                << "ON" << "AND" << "OR" << "NOT" << "IS" << "NULL"
                << "ORDER" << "BY" << "GROUP" << "HAVING" << "AS"
                << "DISTINCT" << "LIMIT" << "OFFSET" << "UNION" << "ALL";
    
    // 创建模型并设置数据
    QStringListModel *model = new QStringListModel(this);
    model->setStringList(sqlKeywords);
    
    // 配置补全器
    completer->setModel(model);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    completer->setCompletionMode(QCompleter::PopupCompletion);
    
    // 为所有现有的SQL编辑器设置补全器
    for (int i = 0; i < count(); ++i) {
        SqlEditor *editor = getSqlEditor(i);
        if (editor) {
            editor->setCompleter(completer);
        }
    }
    
    // 存储补全器指针以备后续使用
    m_sqlCompleter = completer;
}